import React, { useState } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import { upload } from '@/services/ant-design-pro/api'; // 导入你的上传接口

interface RichTextEditorProps {
  value?: string;
  onChange?: (value: string) => void;
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({ value, onChange }) => {
  const handleImageUpload = async (blobInfo: { blob: () => Blob; filename: () => string | undefined; }, progress: any) => new Promise(async (resolve, reject) => {
    const formData = new FormData();
    formData.append('file', blobInfo.blob(), blobInfo.filename());

    try {
      // 使用您的上传接口上传图片
      const response = await upload(formData);

      // 检查响应是否成功
      if (response && response.code === '1' && response.data) {
        const imageUrl = response.data[0]; // 确保 response.data.url 存在
        console.log('Image uploaded successfully:', imageUrl); // 调试日志
        resolve(imageUrl);
      } else {
        reject('Image upload failed: ' + (response && response.message || 'Unknown error'));
      }
    } catch (error) {
      console.error('Image upload error:', error); // 调试日志
      reject('Image upload failed');
    }
  });

  const handleVideoUpload = async (file: File) => new Promise(async (resolve, reject) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      // 使用您的上传接口上传视频
      const response = await upload(formData);

      // 检查响应是否成功
      if (response && response.code === '1' && response.data) {
        const videoUrl = response.data[0]; // 确保 response.data.url 存在
        console.log('Video uploaded successfully:', videoUrl); // 调试日志
        resolve(videoUrl);
      } else {
        reject('Video upload failed: ' + (response && response.message || 'Unknown error'));
      }
    } catch (error) {
      console.error('Video upload error:', error); // 调试日志
      reject('Video upload failed');
    }
  });

  const handleCustomVideoUpload = async (callback, value, meta) => {
    if (meta.filetype === 'media') {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'video/*';
      input.onchange = async (event) => {
        const file = (event.target as HTMLInputElement).files?.[0];
        if (file) {
          const formData = new FormData();
          formData.append('file', file);
  
          try {
            const response = await upload(formData);
            if (response && response.code === '1' && response.data) {
              const videoUrl = response.data[0];
              console.log('Video uploaded successfully:', videoUrl);
              callback(videoUrl, { source2: 'alt.ogg', poster: 'image.jpg' });
            } else {
              console.error('Video upload failed:', response ? response.message : 'Unknown error');
            }
          } catch (error) {
            console.error('Video upload error:', error);
          }
        }
      };
      input.click();
    } else if (meta.filetype === 'image') {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = async (event) => {
        const file = (event.target as HTMLInputElement).files?.[0];
        if (file) {
          const formData = new FormData();
          formData.append('file', file);
  
          try {
            const response = await upload(formData);
            if (response && response.code === '1' && response.data) {
              const imageUrl = response.data[0];
              console.log('Image uploaded successfully:', imageUrl);
              callback(imageUrl, { alt: 'My alt text' });
            } else {
              console.error('Image upload failed:', response ? response.message : 'Unknown error');
            }
          } catch (error) {
            console.error('Image upload error:', error);
          }
        }
      };
      input.click();
    } else if (meta.filetype === 'file') {
      const input = document.createElement('input');
      input.type = 'file';
      input.onchange = async (event) => {
        const file = (event.target as HTMLInputElement).files?.[0];
        if (file) {
          const formData = new FormData();
          formData.append('file', file);
  
          try {
            const response = await upload(formData);
            if (response && response.code === '1' && response.data) {
              const fileUrl = response.data[0];
              console.log('File uploaded successfully:', fileUrl);
              callback(fileUrl, { text: 'My text' });
            } else {
              console.error('File upload failed:', response ? response.message : 'Unknown error');
            }
          } catch (error) {
            console.error('File upload error:', error);
          }
        }
      };
      input.click();
    }
  };
  return (
    <Editor
      tinymceScriptSrc='/tinymce/tinymce.min.js'
      apiKey="gpl" // Replace with your TinyMCE API key
      value={value}
      onEditorChange={(newValue, editor) => {
        if (onChange) {
          onChange(newValue);
        }
      }}
      init={{
        language: 'zh_CN', // Set the editor language to Chinese
        height: 500,
        menubar: false,
        toolbar: [
          'custom  styles insertfile | bold italic underline strikethrough | forecolor backcolor | fontsize | link image media | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | table | custom_video_upload'
        ],
        external_plugins: {
          'image': '/tinymce/plugins/image/plugin.min.js',
          'table': '/tinymce/plugins/table/plugin.min.js',
          'media': '/tinymce/plugins/media/plugin.min.js',
          'link': '/tinymce/plugins/link/plugin.min.js',
        },
        file_picker_callback: handleCustomVideoUpload,
        image_title: true,
        automatic_uploads: true,
        images_upload_handler: handleImageUpload, // Custom image upload handler
        font_size_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
        color_picker_callback: (callback: (color: string) => void, value: string) => {
          // Custom color picker callback
          callback(value);
        },

        setup: (editor: { on: (arg0: string, arg1: () => void) => void; setContent: (arg0: string) => void; }) => {
          editor.on('init', () => {
            editor.setContent(value || '');
          });
        },
      }}
    />
  );
};

export default RichTextEditor;